import { AppDataSource } from "@/config/database";
import { User } from "@/entities/system/user.entity";
import { Context } from "koa";
import { Like } from "typeorm";

export interface IQueryParams {
    /** 页码，默认1 */
    page?: number;

    /** 每页条数，默认10 */
    pageSize?: number;

    /** 排序参数 */
    sorter?: any;

    /** 搜索条件 */
    searchData?: {
        /** 用户名搜索 */
        username?: string;

        /** 昵称搜索 */
        nickname?: string;

        /** 邮箱搜索 */
        email?: string;

        /** 启用状态筛选 */
        enabledStatus?: string;
    }
}

export const getUserList = async (ctx: Context) => {
    const query = ctx.request.body as IQueryParams;

    const {
        page = 1,
        pageSize = 10,
        sorter = {},
        searchData,
    } = query;

    // 参数校验
    const pageNum = Math.max(1, Number(page));
    const pageSizeNum = Math.min(100, Math.max(1, Number(pageSize))); // 限制最大100条

    try {
        const userRepository = AppDataSource.getRepository(User);

        // 构建查询条件
        const where: any = {};

        if (searchData?.username) {
            where.username = Like(`%${searchData?.username}%`);
        }

        if (searchData?.nickname) {
            where.nickname = Like(`%${searchData?.nickname}%`);
        }

        if (searchData?.email) {
            where.email = Like(`%${searchData?.email}%`);
        }

        if (searchData?.enabledStatus) {
            where.enabledStatus = searchData?.enabledStatus;
        }

        // 分页查询
        const [users, total] = await userRepository.findAndCount({
            where,
            select: {
                id: true,
                username: true,
                nickname: true,
                email: true,
                phone: true,
                enabledStatus: true,
                remarks: true,
                createdAt: true,
                updatedAt: true
            },
            order: {
                [sorter.field || 'createdAt']: sorter.order === 'ascend' ? 'ASC' : 'DESC' // 默认按创建时间降序
            },
            skip: (pageNum - 1) * pageSizeNum,
            take: pageSizeNum
        });

        ctx.body = {
            items: users,
            pagination: {
                page: pageNum,
                pageSize: pageSizeNum,
                total,
            }
        };
    } catch (error) {
        console.error('查询用户列表失败:', error);
        ctx.status = 500;
        ctx.body = {
            code: 500,
            message: '服务器错误，查询用户列表失败'
        };
    }
};
